using System;
using System.ComponentModel;
using System.Threading;
using Peepster.Core;
using Peepster.Infrastructure.Twitter;
using Peepster.Properties;

namespace Peepster
{
    public class InputPresenter
    {
        private readonly IInputView _view;
        private readonly ITwitterService _twitter;

        public InputPresenter(IInputView view)
        {
            _view = view;
            _twitter = TwitterClientFactory.Create();
            Settings.Default.PropertyChanged += DefaultPropertyChanged;
        }

        public void Initialize()
        {
            InitializeHotKey();

            if (AppSettings.RunOnWindowsStartUp)
                HideForm();
        }

        public void Close()
        {
            Settings.Default.Save();
        }

        public void SendTweet(string update)
        {
            try
            {
                _twitter.SendTweet(update);
                _view.ClearInput();
                _view.HideView();
            }
            catch (Exception ex)
            {
                _view.SetErrorMessage(ex.Message);
            }
        }

        private void DefaultPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName != "ShortutKey" && e.PropertyName != "ShortcutModifier") return;

            if (AppSettings.GlobalHotKey != null) AppSettings.GlobalHotKey.Dispose();
                InitializeHotKey();
        }

        private void InitializeHotKey()
        {
            AppSettings.GlobalHotKey = new HotKey(AppSettings.ShortCutKey, AppSettings.ShortcutModifier, HotKeyPress);
        }

        private void HotKeyPress(object sender, EventArgs e)
        {
            _view.ShowView();
        }

        private void HideForm()
        {
            ThreadPool.QueueUserWorkItem(state =>
            {
                Thread.Sleep(10);
                _view.HideView();
            });
        }
    }
}